package user

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	"mall/common/errorx"
	"mall/common/jwtx"
	"mall/service/backend/api/internal/logic/backend/util"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/rpc/backendclient"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserInfoLogic {
	return &UserInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserInfoLogic) UserInfo() (resp *types.UserInfoResponse, err error) {
	userId, err := jwtx.GetUserId(l.ctx)
	if err != nil {
		return nil, errorx.Error(errorx.ERROR_NOT_EXIST_PARAME_X_USER_ID, "查询用户失败")
	}

	res, err := l.svcCtx.BackendRpc.GetUserInfo(l.ctx, &backendclient.UserInfoRequest{
		UserId: userId,
	})
	if err != nil {
		return nil, err
	}

	var menus []*types.MenuListItem
	// 组装antd pro中的菜单
	for _, item := range res.Menus {
		menus = append(menus, &types.MenuListItem{
			Id:        item.Id,
			ParentId:  item.ParentId,
			Name:      item.Slug,
			Path:      item.Path,
			Icon:      item.Icon,
			PicUrl:    item.PicUrl,
			Type:      item.Type,
			Url:       item.Url,
			MenuOrder: item.MenuOrder,
		})
	}

	// logrus.Info(fmt.Sprintf("Backend UserInfo userId: %+v ", userId))
	// logrus.Info(fmt.Sprintf("Backend UserInfo apis : %+v ", strings.Join(res.BackendApis, ",")))

	// 把能访问的api存储在redis，在middleware中检验
	err = l.svcCtx.BizRedis.Set(fmt.Sprintf("backend:menu:user%d", userId), strings.Join(res.BackendApis, ","))
	if err != nil {
		logrus.Info(fmt.Sprintf("set backend apis of %s to redis exception: %+v", res.Name, err))
	}

	var tags []*types.ListItem
	if len(res.Tags) > 0 {
		for _, tag := range res.Tags {
			tags = append(tags, &types.ListItem{
				Key:   tag.Key,
				Label: tag.Label,
			})
		}
	}

	return &types.UserInfoResponse{
		Id:               strconv.FormatInt(res.Id, 10),
		Username:         res.Username,
		Nickname:         res.Nickname,
		Name:             res.Name,
		Avatar:           res.Avatar,
		Profile:          res.Profile,
		Signature:        res.Signature,
		Gender:           res.Gender,
		GenderText:       util.GetGenderText(res.Gender),
		Birthday:         res.Birthday,
		Title:            res.Title,
		Group:            res.Group,
		Tags:             tags,
		Country:          res.Country,
		Address:          res.Address,
		Email:            res.Email,
		Mobile:           res.Mobile,
		Phone:            res.Phone,
		Access:           "admin",
		CurrentAuthority: res.CurrentAuthority,
		Menus:            menus,
	}, nil
}
